#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>
#include "Nocopy.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"

namespace UdpServerModule
{
    using namespace LogModule;
    const static uint16_t defaultport = 8888;
    const static int defaultfd = -1;
    const static int defaultsize = 1024;

    class UdpServer : public Nocopy
    {
    public:
        UdpServer(uint16_t port = defaultport)
            :_port(port), _socked(defaultfd) 
        {}

        void Init()
        {
            //1、创建socket套接字，就是创建了文件细节
            _socked = socket(AF_INET, SOCK_DGRAM, 0);
            if(_socked < 0)
            {
                LOG(LogLevel::FATAL) << "socket err";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket success";

            //2、绑定指定网络信息
            struct sockaddr_in local;
            bzero(&local, sizeof(local)); //memset
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY; // 0
            //1. 4字节IP 2.变成网络序列
            // local.sin_addr.s_addr = inet_addr(_ip.c_str()); 

            //结构体填完，填到内核
            int n = ::bind(_socked, (struct sockaddr*)&local, sizeof(local));
            if(n != 0)
            {
                LOG(LogLevel::FATAL) << "bind err";
                exit(BIND_ERR);
            }
        }

        void start()
        {
            //服务器永远不退出
            char buffer[defaultsize];
            for(;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer); // 不能乱写
                ssize_t n = recvfrom(_socked, buffer, sizeof(buffer) - 1, 0,
                (struct sockaddr*)&peer, &len);
                if(n > 0)
                {
                    InetAddr addr(peer);
                    buffer[n] = 0;
                    std::cout << "[" << addr.PrintDebug() << "]# "<< buffer << 
                    std::endl;
                    sendto(_socked, buffer, strlen(buffer), 0, (struct sockaddr*)
                    &peer, len);
                }
            }
        }

        ~UdpServer(){}
        
    private:
        uint16_t _port;
        int _socked;
    };
}